(function() {
    'use strict';

    /**
     * @ngdoc function
     * @region webApp.controller:DeskCtrl
     * @description
     * # DeskCtrl
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('DeskCtrl', DeskCtrl);

    DeskCtrl.$inject = ['$scope', 'dataService', '$timeout', '$location', 'helper', '$document', '$filter', '$state', '$interval', '$rootScope'];


    function DeskCtrl($scope, dataService, $timeout, $location, helper, $document, $filter, $state, $interval, $rootScope) {


        //初始方法
        $scope.listAction = function() {

            $scope.getlist();
            // $scope.$on('event:up-store-id', function() {
            //     $scope.store_id = $rootScope.store_id
            //     // $scope.getItemList(1);
            // });

            // $scope.key = "desk_" + $scope.store_id;
            // console.error(" $scope.key", $scope.key);
            // //加载数据
            // $scope.getuimod().then(function(d) {
            //     if (!d) {
            //         if ($scope.deskData.length <= 0) {
            //             $scope.addDeskData();
            //         }
            //     }
            // });
        }
        $scope.ChoiceTa = function(value) {
            $timeout(function() {
                $scope.desk = value;
            });
        }

        $scope.Delete = function(id) {
            if (id) {
                helper.myConfirm("确认删除?", function() {
                    dataService.tableDelete({ content: { table_id: id } }).then(function(re2) {
                        if (re2.table_id) {
                            helper.myAlert("success");
                            $scope.getlist();

                        } else {
                            helper.myAlert(re2.Msg);
                        }
                    });
                });
            }

        }

        $scope.getlist = function(pageNo) {

            var query = {
                content: {
                    page_no: 1,
                    page_size: 100,
                    store_id: $rootScope.store_id,
                }
            };
            dataService.tableGet(query).then(function(list) {
                if (list.table_list) {
                    $scope.table_list = DivisionData(list.table_list);
                    // $scope.desk = {outer_id:"A" + random()};
                    $scope.tableTotal = list.total_count;
                }
            });
        }

        function DivisionData(data) {

            var subArrayNum = 6;

            var dataArr = new Array(Math.ceil(data.length / subArrayNum)); //取整 除余 然后组成一个空数组 

            console.log('dataArr', dataArr);

            for (var i = 0; i < dataArr.length; i++) {

                dataArr[i] = new Array();
                for (var j = 0; j < subArrayNum; j++) {

                    dataArr[i][j] = '1';

                }

            }

            for (var i = 0; i < data.length; i++) {
                if (data[i]) {
                    dataArr[parseInt(i / subArrayNum)][i % subArrayNum] = data[i];
                }
            }

            for (var i = 0; i < dataArr.length; i++) {
                for (var j = 0; j < dataArr[i].length; j++) {
                    if (dataArr[i][j] == '1') {
                        dataArr[i].splice(j, 1);
                        //s删除的时候必须执行减1 不然j 始终是删除之前的值，没有变化 当前是1的话，删除完j = 0，可以继续往下走，
                        j = j - 1;
                    }
                }
            }
            return dataArr

        }


        //保存
        $scope.save = function() {
            var data = {
                content: {
                    "table_type_id": $scope.desk.table_type_id,
                    "outer_id": $scope.desk.outer_id,
                    "table_id": $scope.desk.table_id,
                    "store_id": $rootScope.store_id
                }
            };

            dataService.tableAdd(data).then(function(r) {
                if (!r.Msg) {
                    helper.myAlert("success", null, null, function() {
                        $scope.getlist();
                    });
                } else {
                    helper.myAlert(r.Msg);
                }
            })

        }

        $scope.delData = function(kk, region) {
            // console.error("kk", kk, region);
            // console.log("$scope.dataList", $scope.dataList);
            _.map($scope.dataList, function(da, ke) {
                if (ke == region) {
                    delete $scope.dataList[ke];
                }
            });
            $scope.deskData.splice(kk, 1);
            var query = { "region": region };
            dataService.tableDelete(query).then(function(list) {
                if (list) {

                }
            });

            console.log("$scope.deskData", $scope.deskData);
        }

        $scope.getuimod = function() {
            $scope.deskData = [];
            $scope.selectData = {};

            var query = {
                page_no: 1,
                page_size: 100
            };
            return dataService.tableGet(query).then(function(result) {
                if (result.tables[0]) {
                    $scope.zhuozi = result.tables;
                    $scope.dataid = result.tables[0].table_id;
                    return dataService.shopconfigGet({ query: { 'field': $scope.key + "_shop" } }).then(function(result2) {
                        if (result2.shopconfigs[0]) {
                            var dd = result2.shopconfigs[0].value;
                            $scope.shopid = result2.shopconfigs[0].shop_config_id;
                            $scope.shop = JSON.parse(dd);
                            $scope.Tpl = {};
                            //根据区分组
                            _.map($scope.zhuozi, function(dd, kk) {
                                if (!$scope.Tpl) {
                                    if (dd.region) {
                                        $scope.Tpl[dd.region].push(dd);
                                    }
                                }
                                if ($scope.Tpl[dd.region]) {
                                    $scope.Tpl[dd.region].push(dd);
                                } else {
                                    if (dd.region) {
                                        $scope.Tpl[dd.region] = [];
                                        $scope.Tpl[dd.region].push(dd);
                                    }
                                }
                            });
                            //组装需要的数组 二维数组
                            _.map($scope.Tpl, function(dd, kk) {
                                if ($scope.shop[kk]) {
                                    $scope.selectData[kk] = { "data": [], "row": $scope.shop[kk].row, "col": $scope.shop[kk].col, "region": kk };
                                    $scope.selectData[kk].data = dd;
                                }
                            });
                            //行数 列数
                            _.map($scope.shop, function(dd, kk) {
                                $scope.deskData.push(dd);
                            });
                            assembleData($scope.selectData);
                            return $scope.deskData;
                        }
                    });
                }
                console.log("$scope.deskData", $scope.deskData);
            });

            $scope.sortableOptions = {
                containment: '#grid-container'
            };
        }

        $scope.addDeskData = function() {
            $scope.init = { "region": "", "row": 0, "col": 0 };
            $scope.deskData.push($scope.init);
        }

        //生成所需要的数据
        $scope.generateData = function(region, fkey) {
            if (region) {
                var i = 1;
                //循环使用的表格数据
                var list = {};
                //一维的数据数组
                $scope.selectData = $scope.selectData ? $scope.selectData : {};
                _.map($scope.deskData, function(isda, ky) {
                    if (region == isda.region) {

                        $scope.selectData[region] = { "data": [], "row": isda.row, "col": isda.col, "region": region };
                        //先循环行 
                        for (i = 1; i <= isda.row; i += 1) {
                            list[i - 1] = [];
                        }

                        var s = 1;
                        //在把列赋值到其中
                        _.map(list, function(data, key) {
                            for (i = 1; i <= isda.col; i += 1) {
                                $scope.selectData[region].data.push({ 'outer_id': "" + s, 'store_id': $scope.store_id, "region": region, "sort": s, "table_type_id": 1, "status": "1", });
                                s += 1;
                            }
                        });
                    }
                });
                assembleData($scope.selectData);
            }
        }

        //把一维数组，拆分为二维数组
        function assembleData(selectData) {
            $scope.dataList = $scope.dataList ? $scope.dataList : {};
            _.map(selectData, function(isda, ky) {
                $scope.dataList[isda.region] = { "data": [], "row": isda.row, "col": isda.col, "region": isda.region };
                for (var i = 1; i <= isda.row; i += 1) {
                    $scope.dataList[isda.region].data[i - 1] = [];
                }

                var s = 0;
                //在把列赋值到其中
                _.map($scope.dataList[isda.region].data, function(data, key) {
                    for (var j = 1; j <= isda.col; j += 1) {
                        data.push(isda.data[s]);
                        s += 1;
                    }
                });
            })
        }

        //判断是否有重复 的值
        $scope.upzid = function(region, sort, nzid, key, value, $event) {

            var data = $scope.dataList[region];
            var type = 0;
            _.map(data.data, function(isda, isky) {
                _.map(isda, function(sub) {
                    if (nzid == sub.zid) {
                        type += 1;
                    }
                });
            });

            if (type >= 2) {
                value.zid = sort;
                helper.myAlert("序号不能重复");
            }
        }

        //生成所需要的数据
        $scope.saveOle = function() {
            var apiAry = {
                "add": "shopConfigAdd",
                "up": "shopConfigUpdate",
            };
            var zhuoziApiAry = {
                "add": "tableAdd",
                "up": "tableUpdate",
            }

            var api = "add";
            var shopconfig = {};
            var zhuoziData = [];
            _.map($scope.dataList, function(data, key) {
                //一个是需要保存到配置的 行列
                shopconfig[data.region] = { "col": data.col, "row": data.row, "region": data.region };
                //一个是保存的数据库的桌子数据
                _.map(data.data, function(svbdata, svbkey) {
                    _.map(svbdata, function(sdata, skey) {
                        zhuoziData.push(sdata);
                    });
                });
            });

            var shopData = { field: $scope.key + "_shop", value: shopconfig };
            if ($scope.shopid) {
                shopData.shop_config_id = $scope.shopid;
            }


            return;
            if ($scope.dataid) {
                api = "up";

            }


            async.map(zhuoziData, function(data, callback) {
                if (data) {
                    dataService[zhuoziApiAry[api]](data).then(function(r) {
                        callback(null);
                    })
                } else {
                    callback(null);
                }
            }, function(e, r) {
                // dataService[apiAry[api]](shopData).then(function(re2) {
                //     helper.myAlert("success");
                // });
            });

        }
    }
})();